package com.tzxx.spider.service;

/*
 * 接收消息的处理类
 *
 * @author Created by tzxx
 * @since : 2019/7/22.
 */

import lombok.extern.slf4j.Slf4j;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import com.tzxx.spider.domain.ArticleLink;
import com.tzxx.spider.domain.Template;
import com.tzxx.spider.spiderbots.base.ParseDetailFactory;

@Slf4j
@Component
public class RedisMessageHandler implements MessageListener {
    @Resource
    private RedisTemplate<Object, Object> redisTemplate;
    @Resource
    private TemplateService templateService;
    @Resource
    private ArticleLinkService articleLinkService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<?> defaultSerializer = redisTemplate.getValueSerializer();
        try {
            Object o = defaultSerializer.deserialize(message.getBody());
            if (o instanceof List) {
                List<ArticleLink> articleLinks = (List<ArticleLink>) o;
                for (ArticleLink articleLink : articleLinks) {
                    articleLinkService.insert(articleLink);
                    Template template = templateService.getTemplateById(articleLink.getTemplateId());
                    ParseDetailFactory.getSpider(template).parseArticleDetail(5, articleLink);
                    log.info("接收到的消息是：{}", articleLink);
                }
            }
        } catch (Exception e) {
            log.error("error:{}", e.getMessage());
        }


    }
}
